﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Form
{
    public partial class ICM_Delivery_Note : System.Web.UI.Page
    {
        IBLLTree bllTree = new TreeBLL();
        IBLLSysYearType bllYearType = new SysYearTypeBLL();
        IBLLMasterPurchaseType bllPurchaseType = new MasterPurchaseTypeBLL();
        IBLLSysRecordStatus bllStatus = new SysRecordStatusBLL();
        IBLLSysProgress bllProgress = new SysProgressBLL();
        DeliveryNoteBLL bllDn = new DeliveryNoteBLL();
        IBLLMasterPurchaseMethod bllMasPurchaseMethod = new MasterPurchaseMethodBLL();
        IBLLPrePurchaseRequest bllPPR = new PrePurchaseRequestBLL();
        SysControlBLL bllSysCon = new SysControlBLL();
        PurchaseOrderInstallmentBLL bllInstallment = new PurchaseOrderInstallmentBLL();
        int ItemsPerRequest = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDefault();
                LoadYearType();
                LoadPurchaseType();
                LoadRecordStatus();
                //LoadOperationName();
                LoadDataGrid();
            }

            if (!string.IsNullOrEmpty(hdPurchaseType.Value))
                hdPurchaseType.Value = hdPurchaseType.Value;
        }

        protected void LoadDefault()
        {
            SysControlInfo infoDefault = bllSysCon.GetDefaultData();

            if (infoDefault.YearType != null)
            {
                cbYearType.SelectedValue = infoDefault.YearType.ToString();
                Session["YearType"] = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            }
            if (infoDefault.Year != null)
            {
                txtYear.Text = infoDefault.Year.ToString();
                Session["Year"] = Convert.ToInt32(txtYear.Text);
            }
        }

        protected void LoadDataGrid()
        {
            Nullable<int> YearTypeSeq = Convert.ToInt32(cbYearType.SelectedValue);
            Nullable<int> Year = (txtYear.Text.Trim() == "") ? null : (Nullable<int>)Convert.ToInt32(txtYear.Text.Trim());
            Nullable<int> PurchaseMethodSeq = (cbPurchaseMethod.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseMethod.SelectedValue) : null;
            Nullable<int> PurchaseTypeSeq = (cbPurchaseType.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseType.SelectedValue) : null;
            Nullable<int> OperationNameSeq = (cbOperationName.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbOperationName.SelectedValue) : null;
            Nullable<int> Status = (cbStatus.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbStatus.SelectedValue) : null;

            IList<DeliveryNoteInfo> infoList = bllDn.GetDeliveryNote(YearTypeSeq, Year, PurchaseMethodSeq, PurchaseTypeSeq, OperationNameSeq, cbStatus.SelectedValue);
            Grid.DataSource = infoList;
            Grid.DataBind();
        }

        protected void LoadYearType()
        {
            IList<SysYearTypeInfo> infoList = bllYearType.GetSysYearType();
            cbYearType.DataSource = infoList;
            cbYearType.DataBind();
        }

        protected void LoadPurchaseType()
        {
            IList<MasterPurchaseTypeInfo> infoList = bllPurchaseType.GetMasterPurchaseType();
            cbPurchaseType.DataSource = infoList;
            cbPurchaseType.DataBind();
        }

        protected void LoadRecordStatus()
        {
            IList<SysRecordStatusInfo> infoList = bllStatus.GetSysRecordStatusTransaction();
            cbStatus.DataSource = infoList;
            cbStatus.DataBind();
        }

        protected void LoadPurchaseMethod(int PurchaseType)
        {
            IList<MasterPurchaseMethodInfo> infoList = bllMasPurchaseMethod.GetMasterPurchaseMethodWithType(PurchaseType);
            cbPurchaseMethod.DataSource = infoList;
            cbPurchaseMethod.DataBind();
        }

        protected void LoadOperationName()
        {
            int PurchaseType = string.IsNullOrEmpty(hdPurchaseType.Value) ? 0 : Int32.Parse(hdPurchaseType.Value);

            IList<HrmEmployeeInfo> infoEmp = bllPPR.GetPrePurchaseRequestOperationName(PurchaseType);
            cbOperationName.DataSource = infoEmp;
            cbOperationName.DataBind();
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            Session["YearType"] = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            Session["Year"] = Convert.ToInt32(txtYear.Text);
            LoadDataGrid();
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<DeliveryNoteInfo> infoList = new List<DeliveryNoteInfo>();
            foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
            {
                DeliveryNoteInfo info = new DeliveryNoteInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllDn.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadDataGrid();
        }

        protected void RadManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            LoadDataGrid();
        }

        protected void Grid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            LoadDataGrid();
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/Personal_Data.ascx"));
        }

        protected void cbPurchaseOrder_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<PurchaseOrderInstallmentInfo> infoList = bllInstallment.GetPurchaseOrderAndInstallmentForDeliveryNote(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbPurchaseOrder.Items.Add(new RadComboBoxItem(infoList[i].InfoPurchaseOrder.Ref_No + " - " + infoList[i].InfoPurchaseOrder.Name, infoList[i].InfoPurchaseOrder.Seq.ToString() + "/" + infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                
                TableCell tdType = new TableCell();
                Label lblType = new Label();
                lblType.Text = infoList[i].InfoPurchaseOrder.InfoPoType.Name;
                tdType.Width = Unit.Pixel(70);
                tdType.Controls.Add(lblType);
                tr.Cells.Add(tdType);
                
                TableCell tdInstall = new TableCell();
                Label lblInstall = new Label();
                lblInstall.Text = infoList[i].InstallNumber.ToString();
                tdInstall.Width = Unit.Pixel(50);
                tdInstall.HorizontalAlign = HorizontalAlign.Center;
                tdInstall.Controls.Add(lblInstall);
                tr.Cells.Add(tdInstall);

                TableCell tdRefNo = new TableCell();
                Label lblRefNo = new Label();
                lblRefNo.Text = infoList[i].InfoPurchaseOrder.Ref_No;
                tdRefNo.Width = Unit.Pixel(100);
                tdRefNo.Controls.Add(lblRefNo);
                tr.Cells.Add(tdRefNo);

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].InfoPurchaseOrder.Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                
                TableCell tdDelivery = new TableCell();
                Label lblDelivery = new Label();
                lblDelivery.Text = String.Format("{0:dd/MM/yyyy}", infoList[i].DeliveryDate);
                tdDelivery.Width = Unit.Pixel(100);
                tdDelivery.Controls.Add(lblDelivery);
                tr.Cells.Add(tdDelivery);

                TableCell tdContact = new TableCell();
                Label lblContact = new Label();
                lblContact.Text = infoList[i].InfoPurchaseOrder.InfoBidder.InfoMasContact.Name_th;
                tdContact.Width = Unit.Pixel(130);
                tdContact.Controls.Add(lblContact);
                tr.Cells.Add(tdContact);

                TableCell tdAmount = new TableCell();
                Label lblAmount = new Label();
                lblAmount.Text = Convert.ToDouble(infoList[i].SumAmount).ToString("###,###,##0.00");
                tdAmount.Width = Unit.Pixel(100);
                tdAmount.Controls.Add(lblAmount);
                tr.Cells.Add(tdAmount);

                ((Table)cbPurchaseOrder.Items[j].FindControl("tablePurchaseOrder")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadDataGrid();
        }

        protected void cbPurchaseMethod_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            int PurTypeSeq = string.IsNullOrEmpty(hdPurchaseType.Value) ? 0 : Int32.Parse(hdPurchaseType.Value);
            
            LoadPurchaseMethod(PurTypeSeq);
        }
        protected void cbOperationName_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadOperationName();
        }
    }
}
